package cn.singlewindow.ha.util.collector.collecter.controller;

import cn.singlewindow.ha.util.collector.integration.component.HandlerModel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.integration.file.FileHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;

@Controller
@RequestMapping("file")
public class FileController {

    private final static Log logger = LogFactory.getLog(FileController.class);

    @RequestMapping
    public String index(){
        return "upload";
    }

    @RequestMapping("upload")
    @ResponseBody
    public Object upload(@RequestParam("files") MultipartFile[] files){
        Object result = "上传成功，正在处理";

        if(Objects.isNull(files)){
            logger.warn(String.format("上传文件列表为空"));
            return String.format("上传文件列表为空");
        }
        for (MultipartFile file: files) {
            Message message = null;
            try {
                message = MessageBuilder.withPayload(file.getBytes())
                        .setHeader(FileHeaders.FILENAME,file.getOriginalFilename())
                        .build();
//                System.err.println(message);
//                logger.info(message);
                new HandlerModel(message).run();
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }

        return result;
    }

}
